﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
using BaHuan.Utils;
namespace BaHuan
{
    public partial class FrmMuaHang : Form
    {
        #region Khai báo biến cục bộ

        private HangHoaManagement hanghoaMgt = new HangHoaManagement();        
        private MuaHangManagement muahangMgt = new MuaHangManagement();  
        private NhaCungCapManagement nhacungcapMgt = new NhaCungCapManagement();
        private CTMuaHangManagement ctmuahangMgt = new CTMuaHangManagement();
        private ChiNhanhCongTyMgt chinhanhctyMgt = new ChiNhanhCongTyMgt();
        private KhoManagement khoMgt = new KhoManagement();
        private QuanLyKhoManagement quanlykhoMgt = new QuanLyKhoManagement();
        private ButToanMgt buttoanMgt = new ButToanMgt();

        private NhaCungCap nhacungcap = new NhaCungCap();       
        private HangHoa hanghoa = new HangHoa();
        private MuaHang muahang = new MuaHang();
        private CTMuaHang ctmuahang = new CTMuaHang();
        private List<CTMuaHang> CTMuaHangNeedDelete = new List<CTMuaHang>();
        private BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();

        private int idLoaiPhieu = 2;
        private NhanVien nhanvien;
        public string sNoiLuu = "";
        public string sOldNoiMuaHang = "";
        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private bool IsEdited = false;
        private bool IsReturned = true;

        public int IsNew = 0;
        public int alter = 0;

        public NhanVien NhanVien
        {
            
            set { this.nhanvien = value; }
            get {return this.nhanvien ;}
        }
        
        public FrmMuaHang(NhanVien nhanvien)
        {
            InitializeComponent();
            IsNew = 1;
            this.NhanVien = nhanvien;
            txtNguoiLapPhieu.Text = nhanvien.HoTen;
        }

        public FrmMuaHang(MuaHang muahang, NhanVien nhanvien)
        {
            InitializeComponent();
            this.muahang = null;
            this.nhanvien = null;
            IsNew = 0;
            this.muahang = muahang;
            this.nhanvien = nhanvien;
        }

        public FrmMuaHang(string noiluu)
        {
            InitializeComponent();
            this.sNoiLuu = noiluu;
        }

        #endregion

        #region Các sự kiện load

        public void ChangeStatusControl(bool IsReadOnly, Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c is TextBox)
                {
                    if (IsReadOnly)
                    {
                        ((TextBox)c).ReadOnly = true;
                    }
                    else
                    {
                        ((TextBox)c).ReadOnly = false;
                    }
                }
                else if (c is ComboBox)
                {
                    if (IsReadOnly)
                    {
                        ((ComboBox)c).Enabled = false;
                        cboPrefix.Enabled = true;
                    }
                    else
                    {
                        ((ComboBox)c).Enabled = true;
                    }
                }
                else if (c is DateTimePicker)
                {
                    if (IsReadOnly)
                    {
                        ((DateTimePicker)c).Enabled = false;
                    }
                    else
                    {
                        ((DateTimePicker)c).Enabled = true;
                    }
                }
            }
        }

        private void FrmMuaHang_Load(object sender, EventArgs e)
        {
            lblId.Text = "";
            dgvMuaHang.AutoGenerateColumns = false;
            lblId.Visible = false;

            cboChiNhanhCty.DataSource = GetAllChiNhanhCty();
            cboChiNhanhCty.DisplayMember = "TenChiNhanh";
            cboChiNhanhCty.ValueMember = "Id";
            cboChiNhanhCty.Enabled = true;

            cboMaKho.DataSource = GetAllKho();
            cboMaKho.DisplayMember = "TenKho";
            cboMaKho.ValueMember = "Id";
            cboMaKho.Enabled = true;
            cboVAT.SelectedIndex = 0;

            cboNhaCungCap.DataSource = GetNhaCungCap();
            cboNhaCungCap.DisplayMember = "TenNhaCungCap";

            cboPrefix.DataSource = GetAllBangMaPhieu(idLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";

            ChangeStatusControl(true, groupBox1);
            dgvMuaHang.ReadOnly = true;
            groupBox1.Enabled = false;
            btnLuu.Enabled = false;
            btnDinhKhoan.Enabled = false;

            dgvMuaHang.Columns["DonGia"].ReadOnly = true;
            dgvMuaHang.Columns["colThanhTien"].ReadOnly = true;

            if (IsNew == 0)
            {
                lblId.Text = muahang.Id.ToString();
                int idct = muahang.IdChiNhanhCongTy;

                ChiNhanhCongTy cnct = (from cn in GetAllChiNhanhCty()
                                       where cn.Id == idct
                                       select cn).First();

                cboChiNhanhCty.Text = cnct.TenChiNhanh;
                sOldNoiMuaHang = cnct.TenChiNhanh;

                dtOld = muahang.NgayThang;
                dtpNgayNhapHang.Value = muahang.NgayThang;

                prefixOld = muahang.Prefix;
                cboPrefix.Text = muahang.Prefix;
                txtMaSo.Text = muahang.OrderNumber;
                
                cboNhaCungCap.Text = muahang.NhaCungCap;
                txtDiachi.Text = muahang.DiaChi;
                txtNVGiaoHang.Text = muahang.NguoiGiaoHang;
                txtDienGiai.Text = muahang.DienGiai;
                txtKemTheo.Text = muahang.ChungTuKemTheo;
                txtNguoiLapPhieu.Text = muahang.NguoiLap;
                cboVAT.Text = muahang.VAT.ToString();
                chkNhapKho.Checked = muahang.IsNhapKho == 0 ? false : true;

                UpdateGridview();

                double SoTien = 0;
                double TongTien = 0;

                for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
                {
                    if (dgvMuaHang.Rows[i].Cells[2] != null && dgvMuaHang.Rows[i].Cells[3] != null)
                    SoTien = Convert.ToDouble(dgvMuaHang.Rows[i].Cells[2].Value.ToString()) * Convert.ToDouble(dgvMuaHang.Rows[i].Cells[3].Value.ToString());
                    TongTien += SoTien;
                }

                lblTongCong.Text = TongTien.ToString();
                lblTienVAT.Text = (TongTien * muahang.VAT / 100).ToString();
            }

            if (txtMaSo.Text != "" || cboPrefix.Text != "")
            {
                btnDinhKhoan.Enabled = true;
                btnSua.Enabled = true;
                btnXoa.Enabled = true;
            }
            else
            {
                btnSua.Enabled = false;
                btnXoa.Enabled = false;
            }
        }

        private void UpdateGridview()
        {
            List<CTMuaHang> lst = (from p in GetAllCTMuaHang()
                                   where p.IdMuaHang == muahang.Id
                                   select p).ToList();

            dgvMuaHang.DataSource = null;
            int i = 0;
            foreach (CTMuaHang ct in lst)
            {
                DataGridViewRow row = new DataGridViewRow();

                DataGridViewCell cell1 = new DataGridViewTextBoxCell();
                cell1.Value = ct.TenHang;
                row.Cells.Add(cell1);
                DataGridViewCell cell2 = new DataGridViewTextBoxCell();
                cell2.Value = ct.DonViTinh;
                row.Cells.Add(cell2);
                DataGridViewCell cell3 = new DataGridViewTextBoxCell();
                cell3.Value = ct.SoLuong;
                row.Cells.Add(cell3);
                DataGridViewCell cell4 = new DataGridViewTextBoxCell();
                cell4.Value = ct.DonGia;
                row.Cells.Add(cell4);
                DataGridViewCell cell5 = new DataGridViewTextBoxCell();
                cell5.Value = (Convert.ToDouble(ct.SoLuong)*Convert.ToDouble(ct.DonGia)).ToString();
                row.Cells.Add(cell5);
                DataGridViewCell cell6 = new DataGridViewTextBoxCell();
                cell6.Value = ct.Id;
                row.Cells.Add(cell6);
                DataGridViewCell cell7 = new DataGridViewTextBoxCell();
                cell7.Value = ct.MaHang;
                row.Cells.Add(cell7);
                DataGridViewCell cell8 = new DataGridViewTextBoxCell();
                cell8.Value = ct.IdMuaHang;
                row.Cells.Add(cell8);

                dgvMuaHang.Rows.Add(row);
                i++;
            }
        }

        private void EnableEdit()
        {
            cboNhaCungCap_SelectedIndexChanged(this.cboNhaCungCap, EventArgs.Empty);

            groupBox1.Enabled = true;
            ChangeStatusTextBox(false);
            btnLuu.Enabled = true;
            txtNguoiLapPhieu.Enabled = false;
            txtNguoiLapPhieu.Text = nhanvien.HoTen;

            cboMaKho.Enabled = true;
            dgvMuaHang.Enabled = true;
            dgvMuaHang.Columns[1].ReadOnly = true;
            //dgvMuaHang.Columns[3].ReadOnly = true;
            dgvMuaHang.Columns[4].ReadOnly = true;
            cboChiNhanhCty.Enabled = true;
            cboVAT.Enabled = true;
            txtMaSo.ReadOnly = true;
            dtpNgayNhapHang.Select();
        }

        private void DisableEdit()
        {
            groupBox1.Enabled = false;
            btnLuu.Enabled = false;
            txtNguoiLapPhieu.Enabled = false;

            cboMaKho.Enabled = false;
            dgvMuaHang.Enabled = false;
            dgvMuaHang.Enabled = false;
            cboChiNhanhCty.Enabled = false;
            cboVAT.Enabled = false;
        }

        public void ChangeStatusTextBox(bool IsReadOnly)
        {
            if (IsReadOnly)
            {
                txtMaSo.ReadOnly = true;
                txtDiachi.ReadOnly = true;
                txtKemTheo.ReadOnly = true;
                dgvMuaHang.ReadOnly = true;
                txtNguoiLapPhieu.ReadOnly = true;

                txtDienGiai.ReadOnly = true;
                cboNhaCungCap.Enabled = false;
                dtpNgayNhapHang.Enabled = true;
                txtNVGiaoHang.ReadOnly = true;
            }
            else
            {
                txtMaSo.ReadOnly = false;
                txtDiachi.ReadOnly = false;
                txtKemTheo.ReadOnly = false;
                txtNguoiLapPhieu.ReadOnly = false;
                txtNguoiLapPhieu.ReadOnly = false;
                dgvMuaHang.ReadOnly = false;
                txtDienGiai.ReadOnly = false;
                cboNhaCungCap.Enabled = true;
                dtpNgayNhapHang.Enabled = true;
                txtNVGiaoHang.ReadOnly = false;
            }
        }

        public void ClearControl(Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c is TextBox)
                {
                    ((TextBox)c).Clear();
                }
                else if (c is ComboBox)
                {
                    switch (c.Name)
                    {
                        case "cboNhaCungCap":
                            cboNhaCungCap.DataSource = GetNhaCungCap();
                            cboNhaCungCap.DisplayMember = "TenNhaCungCap";
                            break;
                    }
                }

                if (c.HasChildren)
                {
                    ClearControl(c);
                }
            }
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        public void BindingToGrid()
        {
            ResultObj result = new ResultObj();

            result = muahangMgt.GetAllMuaHang();
            List<MuaHang> lstMuaHang = (List<MuaHang>)result.Result;

            result = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> listhanghoa = (List<HangHoa>)result.Result;
            dgvMuaHang.DataSource = listhanghoa;
            txtNguoiLapPhieu.Text = nhanvien.HoTen;
        }

        public void frmTimKiemHangHoa_formclosetimkiemhanghoa(string MaSo, string sTen, bool IsReturn)
        {
            this.IsReturned = IsReturn;
            dgvMuaHang.CurrentRow.Cells[0].Value = sTen;
            dgvMuaHang.CurrentRow.Cells[6].Value = MaSo;
        }

        #endregion

        #region Các sự kiện

        private void dgvMuaHang_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void txtNVGiaoHang_TextChanged(object sender, EventArgs e)
        {
            this.Focus();
        }

        private void cboNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<NhaCungCap> lstNhaCungCap = GetNhaCungCap();
            NhaCungCap nhacungcap = (from c in lstNhaCungCap
                                     where c.Id == Convert.ToInt32(((NhaCungCap)cboNhaCungCap.SelectedItem).Id)
                                     select c).FirstOrDefault();

            txtDiachi.Text = nhacungcap.DiaChi;
        }

        private void cboVAT_SelectedIndexChanged(object sender, EventArgs e)
        {
            long tongcong = 0;
            long tienvat = 0;
            this.cboNhaCungCap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

            for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
            {
                tongcong += Convert.ToInt64(dgvMuaHang.Rows[i].Cells[4].Value);
            }

            tienvat = (tongcong * Convert.ToInt64(cboVAT.SelectedItem)) / 100;
            tongcong += tienvat;

            lblTienVAT.Text = tienvat.ToString();
            lblTongCong.Text = tongcong.ToString();
           // cboVAT.SelectedIndex = 0;
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvMuaHang.CurrentRow != null)
            {
                if (!dgvMuaHang.CurrentRow.Cells[5].FormattedValue.Equals(""))
                {
                    int id = Convert.ToInt32(dgvMuaHang.CurrentRow.Cells[5].Value.ToString());
                    CTMuaHang ctDelete = (from ct in GetAllCTMuaHang()
                                              where ct.Id == id
                                              select ct).FirstOrDefault();
                    if (ctDelete != null)
                    {
                        if (!CTMuaHangNeedDelete.Contains(ctDelete))
                        CTMuaHangNeedDelete.Add(ctDelete);
                    }
                }
                if (dgvMuaHang.CurrentRow.Index != (dgvMuaHang.Rows.Count - 1))
                    dgvMuaHang.Rows.RemoveAt(dgvMuaHang.CurrentRow.Index);
            }      
        }

        private void dgvMuaHang_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvMuaHang.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvMuaHang.ClearSelection();
                    dgvMuaHang.CurrentCell = dgvMuaHang.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvMuaHang.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void dgvMuaHang_CellEndEdit(object sender, DataGridViewCellEventArgs e)
            {
            try
            {
                if ((e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4) && e.RowIndex > -1)
                {
                    long num;
                    if (dgvMuaHang.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !Int64.TryParse(dgvMuaHang.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out num))
                    {
                        MessageBox.Show("Vui lòng nhập số !", "Thông báo");
                        dgvMuaHang.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                        return;
                    }
                }

                if (e.ColumnIndex == 0 && e.RowIndex != -1)
                {
                    if (this.IsReturned)
                    {
                        sNoiLuu = ((ChiNhanhCongTy)cboChiNhanhCty.SelectedItem).TenChiNhanh.ToString();
                        string sTimKiem = "";
                        string sMaKho = cboMaKho.Text;
                        if (dgvMuaHang.CurrentRow.Cells[0].Value != null)
                        {
                            sTimKiem = dgvMuaHang.CurrentRow.Cells[0].Value.ToString();

                            HangHoa hh = (from c in GetAllHangHoa()
                                          where c.Ten == sTimKiem && c.NoiLuuTru == ((ChiNhanhCongTy)cboChiNhanhCty.SelectedItem).TenChiNhanh.ToString()
                                          select c).FirstOrDefault();

                            if (hh == null && dgvMuaHang.CurrentRow.Cells[6].Value == null)
                            {
                                FrmTimKiemHangHoa frmTimKiemHangHoa = new FrmTimKiemHangHoa(sTimKiem, sMaKho, sNoiLuu);
                                frmTimKiemHangHoa.formclosetimkiemhanghoa += new FormCloseTimKiemHangHoa(frmTimKiemHangHoa_formclosetimkiemhanghoa);
                                frmTimKiemHangHoa.ShowDialog();
                                this.IsReturned = true;
                            }
                        }

                        if (dgvMuaHang.CurrentRow.Cells[6].Value != null)
                        {
                            HangHoa hanghoa = (from hh in GetAllHangHoa()
                                               where hh.MaSo == dgvMuaHang.CurrentRow.Cells[6].Value.ToString()
                                                     && hh.NoiLuuTru == ((ChiNhanhCongTy)cboChiNhanhCty.SelectedItem).TenChiNhanh.ToString()
                                               select hh).FirstOrDefault();
                            if (hanghoa != null)
                            {
                                dgvMuaHang.Rows[e.RowIndex].Cells[1].Value = hanghoa.DonViTinh;
                                dgvMuaHang.Rows[e.RowIndex].Cells[3].Value = hanghoa.DonGia;
                            }
                            else
                            {
                                MessageBox.Show("Kho không có loại hàng cần tìm", "Thông báo!");
                                dgvMuaHang.CurrentRow.Cells[0].Value = null;
                            }
                        }   
                        else
                            dgvMuaHang.CurrentRow.Cells[0].Value = null;
                    }
                }

                if ((e.ColumnIndex == 2 || e.ColumnIndex == 3) && e.RowIndex != -1)
                {
                    if (dgvMuaHang.Rows[e.RowIndex].Cells[2].Value != null && dgvMuaHang.Rows[e.RowIndex].Cells[3].Value != null)
                    {
                        long thanhtien = 0;
                        long soluong = Convert.ToInt64(dgvMuaHang.Rows[e.RowIndex].Cells[2].Value.ToString());
                        long dongia = Convert.ToInt64(dgvMuaHang.Rows[e.RowIndex].Cells[3].Value.ToString());
                        thanhtien = soluong * dongia;
                        dgvMuaHang.Rows[e.RowIndex].Cells[4].Value = thanhtien.ToString();
                    }
                }

                if (e.RowIndex != -1 && (e.ColumnIndex == 4 || e.ColumnIndex == 2 || e.ColumnIndex == 3))
                {
                    long tongcong = 0;
                    long tienvat = 0;

                    for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
                    {
                        tongcong += Convert.ToInt64(dgvMuaHang.Rows[i].Cells[4].Value);
                    }

                    tienvat = (tongcong * Convert.ToInt64(cboVAT.SelectedItem)) / 100;
                    tongcong += tienvat;

                    lblTienVAT.Text = tienvat.ToString();
                    lblTongCong.Text = tongcong.ToString();
                }
            }
            catch
            {
                return;
            }
        }

        private void cboChiNhanhCty_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboChiNhanhCty.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboChiNhanhCty.Text))
                {
                    cboChiNhanhCty.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboChiNhanhCty.SelectedValue == null)
            {
                cboChiNhanhCty.Text = "";
                cboChiNhanhCty.Focus();
            }
        }

        private void cboChiNhanhCty_SelectedValueChanged(object sender, EventArgs e)
        {
            dgvMuaHang.Rows.Clear();
        } 

        private void cboNhaCungCap_Leave(object sender, EventArgs e)
        {
            foreach (NhaCungCap b in cboNhaCungCap.Items)
            {
                if (b.TenNhaCungCap.ToLower().Contains(cboNhaCungCap.Text))
                {
                    cboNhaCungCap.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboNhaCungCap.SelectedValue == null)
            {
                cboNhaCungCap.Text = "";
                cboNhaCungCap.Focus();
            }
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayNhapHang.Value);
        }

        private void dtpNgayNhapHang_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtpNgayNhapHang.Value)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayNhapHang.Value);
        }

        #endregion

        #region Sự kiện click button

        private void btnThem_Click(object sender, EventArgs e)
        {
            ClearControl(groupBox1);
            IsEdited = false;
            cboVAT.Text = "0" ;

            prefixOld = "";
            dtOld = new DateTime();

            chkNhapKho.Checked = false;
            EnableEdit();
            dgvMuaHang.Rows.Clear();
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            InsertDeleteUpdate();
            btnSua.Enabled = true;
            btnXoa.Enabled = true;
        }

        private void InsertDeleteUpdate()
        {
            if (dgvMuaHang.Rows.Count <= 1)
            {
                MessageBox.Show("Bạn chưa nhập đầy đủ dữ liệu. !!!");
                return;
            }

            for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
            {
                if (dgvMuaHang.Rows[i].Cells[0].Value == null || dgvMuaHang.Rows[i].Cells[2].Value == null || dgvMuaHang.Rows[i].Cells[4].Value == null)
                {
                    MessageBox.Show("Vui lòng nhập đủ thông tin trong danh sách !", "Thông báo");
                    return;
                }
            }

            ResultObj result = new ResultObj();

            string sNguoilap = txtNguoiLapPhieu.Text;
            NhaCungCap nhacungcap = (NhaCungCap)cboNhaCungCap.SelectedItem;
            ChiNhanhCongTy chinhanhcongty = (ChiNhanhCongTy)cboChiNhanhCty.SelectedItem;

            muahang.Prefix = cboPrefix.Text;
            muahang.OrderNumber = txtMaSo.Text;
            muahang.MaSo = cboPrefix.Text + "/" + dtpNgayNhapHang.Value.ToString("MM") + dtpNgayNhapHang.Value.ToString("yy") + "/" + txtMaSo.Text;
            muahang.History = "";

            string sNhaCungCap = nhacungcap.TenNhaCungCap;
            DateTime sngaythang = dtpNgayNhapHang.Value;
            string sDiachi = txtDiachi.Text;
            string sNvgiaohang = txtNVGiaoHang.Text;
            string sDiengiai = txtDienGiai.Text;
            string sKemtheo = txtKemTheo.Text;
            int isNhapKho = 0;
            if (chkNhapKho.Checked)
                isNhapKho = 1;

            muahang.NguoiLap = sNguoilap;
            muahang.DiaChi = sDiachi;
            muahang.NguoiGiaoHang = sNvgiaohang;
            muahang.DienGiai = sDiengiai;
            muahang.ChungTuKemTheo = sKemtheo;
            muahang.NhaCungCap = sNhaCungCap;
            muahang.IdChiNhanhCongTy = Convert.ToInt32(cboChiNhanhCty.SelectedValue.ToString());
            muahang.NgayThang = sngaythang;
            muahang.VAT = Convert.ToInt64(cboVAT.SelectedItem.ToString());
            muahang.TienVAT = Convert.ToInt64(lblTienVAT.Text);
            muahang.TongCong = Convert.ToInt64(lblTongCong.Text);
            muahang.IsNhapKho = isNhapKho;

            //Insert
            if (!IsEdited)
            {
                result = muahangMgt.SaveNewMuaHang(muahang);
                lblId.Text = result.ReturnCode.ToString();

                for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
                {
                    CTMuaHang ctMuahang = new CTMuaHang();
                    ctMuahang.IdMuaHang = Convert.ToInt32(lblId.Text);
                    ctMuahang.TenHang = dgvMuaHang.Rows[i].Cells[0].FormattedValue.ToString();
                    ctMuahang.MaHang = Convert.ToString(dgvMuaHang.Rows[i].Cells[6].Value);
                    ctMuahang.DonViTinh = dgvMuaHang.Rows[i].Cells[1].Value.ToString();
                    ctMuahang.SoLuong = Convert.ToInt64(dgvMuaHang.Rows[i].Cells[2].Value);
                    ctMuahang.DonGia = Convert.ToInt64(dgvMuaHang.Rows[i].Cells[3].Value);

                    result = ctmuahangMgt.SaveNewCTMuaHang(ctMuahang);
                    dgvMuaHang.Rows[i].Cells[5].Value = result.ReturnCode;
                }
            }
            //Update
            else
            {
                List<CTMuaHang> lst = (from p in GetAllCTMuaHang()
                                       where p.IdMuaHang == Convert.ToInt32(lblId.Text)
                                       select p).ToList();

                List<QuanLyKho> QLKho = (from k in GetAllQuanLyKho()
                                         where k.SoChungTuNhap == muahang.MaSo
                                         select k).ToList();

                foreach (QuanLyKho qlk in QLKho)
                {
                    qlk.IsDelete = 1;
                    result = quanlykhoMgt.UpdateQuanLyKho(qlk);

                    HangHoa hanghoa = (from h in GetAllHangHoa()
                                       where h.Id == qlk.IdHangHoa && h.NoiLuuTru == sOldNoiMuaHang
                                       select h).FirstOrDefault();

                    int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                    hanghoa.SoLuong -= lst[index].SoLuong;
                    result = hanghoaMgt.UpdateHangHoa(hanghoa);
                }

                muahang.Id = Convert.ToInt32(lblId.Text);
                result = muahangMgt.UpdateMuaHang(muahang);

                for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
                {
                    ctmuahang.Id = Convert.ToInt32(dgvMuaHang.Rows[i].Cells[5].Value);
                    ctmuahang.IdMuaHang = muahang.Id;
                    ctmuahang.TenHang = dgvMuaHang.Rows[i].Cells[0].FormattedValue.ToString();
                    ctmuahang.MaHang = Convert.ToString(dgvMuaHang.Rows[i].Cells[6].Value);
                    ctmuahang.DonViTinh = dgvMuaHang.Rows[i].Cells[1].Value.ToString();
                    ctmuahang.SoLuong = Convert.ToInt64(dgvMuaHang.Rows[i].Cells[2].Value);
                    ctmuahang.DonGia = Convert.ToInt64(dgvMuaHang.Rows[i].Cells[3].Value);
                    ctmuahang.IsDelete = muahang.IsDelete;

                    if (dgvMuaHang.Rows[i].Cells[5].Value != null)
                    {
                        ctmuahang.Id = Convert.ToInt32(dgvMuaHang.Rows[i].Cells[5].Value);
                        result = ctmuahangMgt.UpdateCTMuaHang(ctmuahang);
                    }
                    else
                    {
                        result = ctmuahangMgt.SaveNewCTMuaHang(ctmuahang);
                        dgvMuaHang.Rows[i].Cells[5].Value = result.ReturnCode;
                    }
                }

                IsEdited = false;
            }

            if (result.ReturnCode > 0)
            {
                if (IsEdited)
                {
                    EditOrRemoveDinhKhoan(muahang.MaSo);
                    MessageBox.Show("Vui lòng cập nhật lại các bút toán kế toán");
                }

                for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
                {
                    if (dgvMuaHang.Rows[i].Cells[0].Value != null && dgvMuaHang.Rows[i].Cells[2].Value != null && dgvMuaHang.Rows[i].Cells[4].Value != null)
                    {
                        List<HangHoa> lstHangHoa = (from hh in GetAllHangHoa()
                                                    where hh.Id == Convert.ToInt32(dgvMuaHang.Rows[i].Cells[5].Value) &&
                                                    hh.NoiLuuTru == ((ChiNhanhCongTy)cboChiNhanhCty.SelectedItem).TenChiNhanh.ToString()
                                                    select hh).ToList();

                        if (lstHangHoa.Count > 0)
                        {
                            lstHangHoa[0].SoLuong += Convert.ToInt32(dgvMuaHang.Rows[i].Cells[2].Value.ToString());
                            hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                        }
                    }
                }

                MessageBox.Show("Lưu thành công", "Thông báo");

                //*** Insert vao quan ly kho
                List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                where q.SoChungTuNhap == muahang.MaSo
                                                select q).ToList(); 
                if (lstQuanLykho.Count > 0)
                    return;

                ResultObj resObj = new ResultObj();
                List<Kho> lstKho = (from k in GetAllKho()
                                    where k.TenKho == ((Kho)cboMaKho.SelectedItem).TenKho
                                    select k).ToList();
                for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
                {
                    string tenhang = dgvMuaHang.Rows[i].Cells[0].Value.ToString();

                    HangHoa hanghoa = (from h in GetAllHangHoa()
                                       where h.Ten == tenhang && h.NoiLuuTru == cboChiNhanhCty.Text
                                       select h).FirstOrDefault();

                    if (lstKho.Count > 0)
                    {
                        QuanLyKho quanlykho = new QuanLyKho();
                        quanlykho.IdKho = lstKho[0].Id;
                        quanlykho.IdHangHoa = hanghoa.Id;

                        string pre = cboPrefix.Text;
                        string order = txtMaSo.Text;
                        string ma = cboPrefix.Text + "/" + dtpNgayNhapHang.Value.ToString("MM") + dtpNgayNhapHang.Value.ToString("yy") + "/" + txtMaSo.Text;

                        quanlykho.SoChungTuNhap = ma;
                        quanlykho.SoChungTuXuat = "";

                        resObj = quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                    }
                }

                alter = 0;
                if (CTMuaHangNeedDelete.Count > 0)
                {
                    foreach (CTMuaHang ct in CTMuaHangNeedDelete)
                    {
                        ct.IsDelete = 1;
                        ctmuahangMgt.UpdateCTMuaHang(ct);
                    }
                    CTMuaHangNeedDelete.Clear();
                }

                DisableEdit();
                btnLuu.Enabled = false;
                btnDinhKhoan.Enabled = true;

            }
            else if (result.ReturnCode == Definitions.DUPLICATED_VALUE)
            {
                MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                if (!IsEdited)
                {
                    muahang.Id = Convert.ToInt32(lblId.Text);
                    muahangMgt.DeleteMuaHang(muahang);
                }
            }
            else
            {
                MessageBox.Show("Thất bại");
                if (!IsEdited)
                {
                    muahang.Id = Convert.ToInt32(lblId.Text);
                    muahangMgt.DeleteMuaHang(muahang);
                }
            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            btnSua.Enabled = false;
            EnableEdit();
            btnXoa.Enabled = false;
            btnLuu.Enabled = true;
            IsEdited = true;
            alter = 1;
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Bạn chắc chắn muốn xóa?", "Thông báo!", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                ResultObj resultObj = new ResultObj();

                //Xóa mua hàng (đổi IsDelete = 1)
                muahang.IsDelete = 1;
                IsEdited = true;
                muahangMgt.UpdateMuaHang(muahang);

                //Xóa chi tiết mua hàng
                List<CTMuaHang> lst = (from p in GetAllCTMuaHang()
                                       where p.IdMuaHang == muahang.Id
                                       select p).ToList();

                foreach (CTMuaHang ct in lst)
                {
                    ct.IsDelete = 1;
                    ctmuahangMgt.UpdateCTMuaHang(ct);
                }

                //Xóa định khoản
                EditOrRemoveDinhKhoan(muahang.MaSo);

                //Xóa hàng trong Kho
                List<QuanLyKho> QLKho = (from k in GetAllQuanLyKho()
                                         where k.SoChungTuNhap == muahang.MaSo
                                         select k).ToList();

                foreach (QuanLyKho qlk in QLKho)
                {
                    qlk.IsDelete = 1;
                    resultObj = quanlykhoMgt.UpdateQuanLyKho(qlk);

                    HangHoa hanghoa = (from h in GetAllHangHoa()
                                       where h.Id == qlk.IdHangHoa && h.NoiLuuTru == ((ChiNhanhCongTy)cboChiNhanhCty.SelectedItem).TenChiNhanh
                                       select h).FirstOrDefault();

                    int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                    hanghoa.SoLuong -= lst[index].SoLuong;
                    resultObj = hanghoaMgt.UpdateHangHoa(hanghoa);
                }

                MessageBox.Show("Đã xóa", "Thông báo!");
            }
            else if (dialogResult == DialogResult.No)
            {
                return;
            }
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            MuaHang muahang = new MuaHang();

            string pre = cboPrefix.Text;
            string order = txtMaSo.Text;
            string ma = cboPrefix.Text + "/" + dtpNgayNhapHang.Value.ToString("MM") + dtpNgayNhapHang.Value.ToString("yy") + "/" + txtMaSo.Text;

            muahang.MaSo = ma;
            muahang.NguoiLap = txtNguoiLapPhieu.Text;
            muahang.NguoiGiaoHang = txtNVGiaoHang.Text;
            muahang.DiaChi = txtDiachi.Text;
            muahang.DienGiai = txtDienGiai.Text;
            muahang.ChungTuKemTheo = txtKemTheo.Text;
            muahang.NhaCungCap = ((NhaCungCap)cboNhaCungCap.SelectedItem).TenNhaCungCap;
            muahang.IdChiNhanhCongTy = Convert.ToInt32(cboChiNhanhCty.SelectedValue.ToString());
            muahang.VAT = Convert.ToInt64(cboVAT.SelectedItem.ToString());
            muahang.TienVAT = Convert.ToInt64(lblTienVAT.Text);
            muahang.TongCong = Convert.ToInt64(lblTongCong.Text);
            muahang.listCTMuaHang = new List<CTMuaHang>();

            for (int i = 0; i < dgvMuaHang.Rows.Count - 1; i++)
            {
                CTMuaHang ctmuahang = new CTMuaHang();
                ctmuahang.TenHang = dgvMuaHang.Rows[i].Cells[0].Value.ToString();
                ctmuahang.DonViTinh = dgvMuaHang.Rows[i].Cells[1].Value.ToString();
                ctmuahang.SoLuong = Convert.ToInt64(dgvMuaHang.Rows[i].Cells[2].Value);
                ctmuahang.DonGia = Convert.ToInt64(dgvMuaHang.Rows[i].Cells[3].Value);
                muahang.listCTMuaHang.Add(ctmuahang);
            }

            FrmDinhKhoanMuaHang frmdinhkhoanmuahang = new FrmDinhKhoanMuaHang();
            frmdinhkhoanmuahang.MuaHang = muahang;
            frmdinhkhoanmuahang.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region Lấy thông tin từ database

        public List<HangHoa> GetAllHangHoa()
        {
            ResultObj obj = new ResultObj();

            obj = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> listHangHoa = (List<HangHoa>)obj.Result;

            return listHangHoa;
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCty()
        {
            ResultObj resultObj = new ResultObj();

            List<ChiNhanhCongTy> lstChiNhanhCongTy = new List<ChiNhanhCongTy>();

            resultObj = chinhanhctyMgt.GetAllChiNhanhCongTy();
            lstChiNhanhCongTy = (List<ChiNhanhCongTy>)resultObj.Result;

            return lstChiNhanhCongTy;
        }

        public List<CTMuaHang> GetAllCTMuaHang()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = ctmuahangMgt.GetAllCTMuaHang();
            List<CTMuaHang> listCTMuaHang = (List<CTMuaHang>)resultObj.Result;

            return listCTMuaHang;
        }

        public List<NhaCungCap> GetNhaCungCap()
        {
            ResultObj resultObj = new ResultObj();
            List<NhaCungCap> lstNhaCungCap = new List<NhaCungCap>();

            resultObj = nhacungcapMgt.GetAllNhaCungCap();
            lstNhaCungCap = (List<NhaCungCap>)resultObj.Result;

            return lstNhaCungCap;
        }

        public List<Kho> GetAllKho()
        {
            ResultObj resultObj = new ResultObj();
            List<Kho> lstKho = new List<Kho>();

            resultObj = khoMgt.GetAllKho();
            lstKho = (List<Kho>)resultObj.Result;

            return lstKho;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<QuanLyKho> GetAllQuanLyKho()
        {
            ResultObj resultObj = new ResultObj();
            List<QuanLyKho> lstQuanLyKho = new List<QuanLyKho>();

            resultObj = quanlykhoMgt.GetAllQuanLyKho();
            lstQuanLyKho = (List<QuanLyKho>)resultObj.Result;

            return lstQuanLyKho;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }

        #endregion
    }
}
